package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Menu;
import com.qf.entity.Role;
import com.qf.entity.User;
import com.qf.mapper.UserMapper;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import com.qf.utils.MenuUtil;
import com.qf.utils.NumberUtil;
import com.qf.utils.RoleExcleUtil;
import com.qf.utils.UserExcleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 2019/12/11
 * 郭程鹏
 * springboot_oa_five
 * 面向代码面向君,不负时光不负卿
 */
@Controller
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserMapper userMapper;

    //角色 分页 模糊
    @RequestMapping("/resource/system/role/list")
    public String findAllUsers(Model model, @RequestParam(defaultValue = "") String roleName,@RequestParam(defaultValue = "1") Integer page){

        PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("roleName",roleName);

        return "resource/system/role/list";
    }



    //导出excle +批量删除
    @RequestMapping("/resource/system/role/deleteAndExcle")
    public void findAllRoels(@RequestParam("roleId")List<Integer> roleId, @RequestParam("method") String method, HttpServletResponse response){

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream outputStream=null;


            if (method.equals("doExcle")){

                try {
                    List<Role> excle = roleService.getExcle(roleId);
                    outputStream = response.getOutputStream();

                    //生成随机名字
                    String number = NumberUtil.getNumber(6);
                    //设置导出格式
                    response.setContentType("application/x-download");
                    String excleName = "excle_"+number+ ".xls";
                    response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
                    //设置表名
                    RoleExcleUtil.createFirstRow("用户信息");
                    //设置类容
                    RoleExcleUtil.createSheetValue(excle);
                    RoleExcleUtil.export(outputStream);
                    outputStream.flush();
                    outputStream.close();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }else if(method.equals("deleteAll")){

                List<Integer> list = roleService.checkDelDo(roleId);
                if (list.size()>0){
                    StringBuilder builder = new StringBuilder();
                    List<String> roleNameByUserId = roleService.findRoleNameByUserId(list);

                    for (String s : roleNameByUserId) {
                        builder.append(s+"、");
                    }


                    try {
                        response.getWriter().print("<script>alert('"+builder+"角色正在使用，没有权限删除!');window.history.back();</script>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        roleService.deleteAll(roleId);

                        response.getWriter().print("<script>alert('删除成功');location.href='/resource/system/role/list';</script>");
                    } catch (IOException e) {
                        try {
                            response.getWriter().print("<script>alert('删除失败');location.href='/resource/system/role/list';</script>");
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        e.printStackTrace();
                    }
                }



            }



    }

    //删除一条数据

    @RequestMapping("/resource/system/role/deleteOne")
    public String deleteOne(Model model,@RequestParam("roleId") Integer roleId, @RequestParam(defaultValue = "") String roleName,@RequestParam(defaultValue = "1") Integer page,HttpServletResponse response){

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        List<String> strings = roleService.checkCanDel(roleId);
        if (strings.size()>0){
            try {
                response.getWriter().print("<script>alert('角色正在使用不能删除!');</script>");
                PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
                model.addAttribute("pageInfo",pageInfo);
                model.addAttribute("roleName",roleName);
                return "resource/system/role/list";

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                roleService.deleteOne(roleId);
                roleService.delMenuIdByUserIdInMiddle(roleId);
                response.getWriter().print("<script>alert('删除成功');</script>");
                PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
                model.addAttribute("pageInfo",pageInfo);
                model.addAttribute("roleName",roleName);
                return "resource/system/role/list";

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    response.getWriter().print("<script>alert('删除失败');</script>");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        }

        return null;
    }


    //禁用
  @RequestMapping("/resource/system/role/updateOne")
    public String updateOne(Model model,@RequestParam("roleId") Integer roleId, @RequestParam(defaultValue = "") String roleName,@RequestParam(defaultValue = "1") Integer page,HttpServletResponse response){
      response.setCharacterEncoding("utf-8");
      response.setContentType("text/html;charset=utf-8");

          try {
              roleService.updateOne(roleId);
              PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
              model.addAttribute("roleName",roleName);

              model.addAttribute("pageInfo",pageInfo);
              response.getWriter().print("<script>alert('角色已禁用!');</script>");
              return "resource/system/role/list";


          } catch (Exception e) {
              e.printStackTrace();
              try {
                  response.getWriter().print("<script>alert('禁用失败!');</script>");
                  PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
                  model.addAttribute("roleName",roleName);

                  model.addAttribute("pageInfo",pageInfo);
                  return "resource/system/role/list";
              } catch (IOException ex) {
                  ex.printStackTrace();
              }
          }
          return null;
      }

    //启用
    @RequestMapping("/resource/system/role/roleActive")
    public String roleActive(Model model,@RequestParam("roleId") Integer roleId, @RequestParam(defaultValue = "") String roleName,@RequestParam(defaultValue = "1") Integer page,HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
            roleService.activeOne(roleId);
            PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
            model.addAttribute("roleName",roleName);

            model.addAttribute("pageInfo",pageInfo);
            response.getWriter().print("<script>alert('角色已启用!');</script>");
            return "resource/system/role/list";
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().print("<script>alert('禁用失败!');</script>");
                PageInfo<Role> pageInfo = roleService.findAllRoles(roleName, page);
                model.addAttribute("roleName",roleName);

                model.addAttribute("pageInfo",pageInfo);
                return "resource/system/role/list";
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

  //角色添加前信息回显
  @RequestMapping("/resource/system/role/preAdd")
    public String preAddrole(Model model){
        //菜单
      List<Menu> menu = roleService.findMenu();

        model.addAttribute("menu",menu);
      return "resource/system/role/add";
    }

    //异步校验菜单名
    @RequestMapping("/resource/system/role/ajaxRole")
    @ResponseBody
    public Integer ajaxRole(@RequestParam("roleName") String roleName){

        Integer integer = roleService.ajaxRoleName(roleName);
        return integer;
    }


    //添加角色和中间表
    @RequestMapping("/resource/system/role/addRole")
    public void addRole(HttpServletResponse response,Role role,@RequestParam("menuId")List<Integer> menuId) throws IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Integer integer = null;
        try {
            integer = roleService.addRoleAndMiddle(role, menuId);
            if (integer>0){
                response.getWriter().print("<script>alert('添加角色成功!');window.history.back();</script>");
            }else {
                response.getWriter().print("<script>alert('添加角色失败!');window.history.back();</script>");
            }
        } catch (Exception e) {
            response.getWriter().print("<script>alert('添加角色失败!');window.history.back();</script>");
            e.printStackTrace();
        }



    }


    //修改角色预览
    @RequestMapping("/resource/system/role/preEdit")
    public String preEdit(Model model,@RequestParam("roleId") Integer roleId){
        Role role = roleService.findRoleById(roleId);
        model.addAttribute("role",role);
        List<Menu> menu = roleService.findMenu();
        List<Menu> menuByRoleId = userMapper.findMenuByRoleId(roleId);
        List<Menu> firstMenu = MenuUtil.firstMenu(menuByRoleId);

        model.addAttribute("menu",menu);
        model.addAttribute("oldMenu",firstMenu);

        return "resource/system/role/edit";
    }


    //修改角色
    @RequestMapping("/resource/system/role/edit")
    public void editRole(HttpServletResponse response,Role role,@RequestParam("menuId")List<Integer> menuId){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Integer middle = roleService.updateRoleAndMiddle(role, menuId);
        if (middle>0){
            try {
                response.getWriter().print("<script>alert('修改成功!');window.history.back();</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                response.getWriter().print("<script>alert('修改失败!');window.history.back();</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //查看角色
    @RequestMapping("/resource/system/role/look")
    public String lookRole(Integer roleId,Model model){

        Role role = roleService.findRoleById(roleId);
        List<Menu> firstMenu = roleService.findMenuByRoelId(roleId);

        model.addAttribute("role",role);
        model.addAttribute("lookMenu",firstMenu);

        return "resource/system/role/look";
    }
}
